package com.mycode.test;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.mycode.util.ByteBufferUtil.debugAll;

/**
 * @auther yuanpengtao
 * @email 1294776572@qq.com
 * @data 2024/3/6 22:55
 */
@Slf4j
public class AioFileChannel {

    public static void main(String[] args) {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("nio-demo/src/data.txt"), StandardOpenOption.READ)) {
            //
            ByteBuffer buffer = ByteBuffer.allocate(16);
            Thread.currentThread().setName("aioFile");
            /**
             * ByteBuffer dst,
             * long position, 读取的起始位置
             * A attachment,  附件
             * CompletionHandler<Integer,? super A> handler 回调对象
             */
            log.debug("read begin ... ");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                // read 成功
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed ... ");
                    log.debug("Thread {}, 守护线程：{}", Thread.currentThread().getName(), Thread.currentThread().isDaemon());
                    attachment.flip();
                    debugAll(attachment);
                }

                //read 失败
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end ... ");
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
